<template>
    <div>
        <!--先选择游戏  前置弹窗-->
        <el-dialog class="add_dialog" :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false"
            append-to-body fullscreen @close="close" :close-on-press-escape="false">
            <div class="add-edit-box">
                <span class="ceshifont"> </span>
                <div class="flex">
                    <div class="form-box">
                        <div class="sub-tit">
                            <formSubTitVue :title="'账号信息'" />
                        </div>
                        <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="80px"
                            class="demo-ruleForm new_form_box">
                            <el-form-item label="游戏名称" prop="gameId">
                                <el-select :disabled="isEdit" filterable clearable v-model="form.gameId"
                                    placeholder="请选择游戏名称" @change="gameChange">
                                    <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name"
                                        :value="dict.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="游戏区服" prop="qufuIds">
                                <el-cascader :disabled="isView" @change="qufuChange" filterable clearable
                                    v-model="form.qufuIds" :options="qufuTree" :props="qufuProps"></el-cascader>
                            </el-form-item>
                            <el-form-item label="自编号" prop="selfNumber">
                                <el-input type="text" v-model="form.selfNumber" placeholder="自己编写的编号,限20位"
                                    :disabled="isView" maxlength="20" />
                            </el-form-item>
                            <el-form-item label="是否自营" prop="goodsType">
                                <el-radio-group v-model="form.goodsType" :disabled="isView">
                                    <el-radio :label="1">自营</el-radio>
                                    <el-radio :label="2">代售</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <!-- <el-form-item label="价格" label-width="50px" prop="price"> -->
                                <!-- <div class="price-group flex"> -->
                                    <el-form-item  label="时租价格" label-width="80px" prop="price">
                                        <span class="price-label">时租</span>
                                        <el-input v-model="form.price" placeholder="请输入" :disabled="isView"
                                            style="width: 100px;" />
                                    </el-form-item>
                                    <el-form-item prop="priceDay" label="日租价格" label-width="80px">
                                        <span class="price-label">日租(24小时)</span>
                                        <el-input v-model="form.priceDay" placeholder="请输入" :disabled="isView"
                                            style="width: 100px;" />
                                    </el-form-item>
                                    <el-form-item prop="priceWeek" label="周租价格" label-width="80px">
                                        <span class="price-label">周租(168小时)</span>
                                        <el-input v-model="form.priceWeek" placeholder="请输入" :disabled="isView"
                                            style="width: 100px;" />
                                    </el-form-item>
                                <!-- </div> -->
                            <!-- </el-form-item> -->
                            
                            <el-form-item label="是否有预付款" prop="isSub" label-width="100px">
                                <el-radio-group v-model="form.isSub" :disabled="isView">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="2">否</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item v-if="form.isSub == 1" label="预付款金额" prop="priceSub" label-width="100px">
                                <el-input type="text" v-model="form.priceSub" placeholder="请输入预付款" :disabled="isView" />
                            </el-form-item>


                            <el-form-item label="商品标题" prop="title" class="row">
                                <el-input type="textarea" rows="2" v-model="form.title" placeholder="请输入商品标题，最多200个字"
                                    maxlength="200" show-word-limit :disabled="isView" />
                            </el-form-item>


                            <el-form-item class="row" label="商品主图" prop="">

                                <div class="" :class="{ hiddenupload: titleImgList.length }">
                                    <el-input v-model="form.titleImg" v-show="false"></el-input>
                                    <el-upload class :action="uploadImgUrl" :file-list="titleImgList"
                                        :show-file-list="true" list-type="picture-card" :limit="1"
                                        accept="image/png, image/jpeg" :on-success="handleAvatarSuccess"
                                        :on-remove="handleAvatarRemove" :http-request="uploadImgs"
                                        :on-preview="handlePictureCardPreview" :disabled="isView"
                                        :before-upload="beforeUploadImg">
                                        <div class="uploadbg">
                                            <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png"
                                                alt="">
                                            <br />
                                            <span>选择图片</span>
                                        </div>
                                    </el-upload>
                                    <div class="flex alc">
                                        <saomaUpload @success="saomaEnd($event, 'titleImg')">
                                            <el-button style="width:100px" type="primary" plain v-if="!isView">
                                                扫码上传</el-button>
                                        </saomaUpload>
                                        <el-button v-if="!isView" type="primary" style="width:100px;margin-left: 10px;"
                                            @click="openGetInfoDialog" :loading="makeTitleImgBtnLoading">
                                            首图生成</el-button>
                                    </div>

                                </div>
                            </el-form-item>

                            <el-form-item label="详情图片" class="row">
                                <div class="">
                                    <!-- 自定义拖拽排序 -->
                                    <draggable v-model="imgFileList">
                                        <transition-group class="uploader">
                                            <div v-for="(item, index) in imgFileList" :key="index" class="upload-list">
                                                <img v-if="item.url" style="width: 100%; height: 100%" :src="item.url.indexOf('blob:') > -1
                                                    ? item.response && item.response.data
                                                        ? item.response.data.filePath
                                                        : item.url
                                                    : item.url
                                                    " />
                                                <img class="imgs" v-if="item.url" style="width: 30px"
                                                    src="../../../assets/img/shangchuan.png" alt="" />
                                                <div class="icon-container">
                                                    <span v-if="item.url" @click="handlePreviewNew(index)">
                                                        <i class="el-icon-zoom-in"></i>
                                                    </span>
                                                    <span v-if="item.url && (!isView || isEdit)"
                                                        @click="handleRemove(item.url)">
                                                        <i class="el-icon-delete"></i>
                                                    </span>
                                                </div>
                                            </div>
                                        </transition-group>
                                    </draggable>
                                    <el-upload :action="uploadImgUrl" :file-list="imgFileList" list-type="picture-card"
                                        :show-file-list="false" :on-preview="handlePictureCardPreview"
                                        :on-exceed="uploadNumber" :multiple="true" :drag="true"
                                        :before-upload="beforeUploadImg" :on-success="handleUploadSuccess" :limit="100"
                                        accept="image/png, image/jpeg" :on-remove="handleRemove"
                                        :http-request="uploadImgs" :disabled="isView">
                                        <div class="uploadbg">
                                            <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png"
                                                alt="">
                                            <br />
                                            <span>选择图片</span>
                                        </div>
                                    </el-upload>

                                    <div class="flex alc">
                                        <saomaUpload @success="saomaEnd($event, 'detailImg')">
                                            <el-button style="width:100px" type="primary" plain v-if="!isView">
                                                扫码上传</el-button>
                                        </saomaUpload>
                                        <el-button style="width:150px;margin-left: 10px;" type="primary"
                                            @click="getDetailImgs" :loading="makeDetailImgBtnLoading"
                                            v-if="!isView && form.gameId != 7">
                                            详情图生成</el-button>
                                    </div>
                                </div>
                            </el-form-item>
                            <div class=" step-box ">
                                <formSubTitVue :title="'基础信息'" />
                                <el-form-item label="账号" prop="account">
                                    <el-input v-model="form.account" placeholder="请输入账号" :disabled="isView" />
                                </el-form-item>
                                <el-form-item label="密码" prop="password">
                                    <el-input v-model="form.password" placeholder="请输入密码" :disabled="isView" />
                                </el-form-item>
                                <el-form-item class="row" label="其他信息" prop="otherInfo">
                                    <el-input v-model="form.otherInfo" type="textarea"
                                        placeholder="可以记录密保信息，采购渠道 包赔信息 卖家信息等，任意重要信息都可以放到此处 方便查找 限制500个字符" :rows="2"
                                        :disabled="isView" show-word-limit maxlength="500" />
                                </el-form-item>
                            </div>
                        </el-form>
                    </div>
                    <div class="release-page">
                        <releaseTool :formData="infoData" :isEdit="isEdit" :isView="isView" @submit="getInfoData"
                            @setTitle="setTitle" ref="releaseTool" :retal="true" @attrChange="attrChange">
                        </releaseTool>
                    </div>
                </div>

                <div class="center">
                    <el-button class="font16" plain type="" @click="closeFn('')">关 闭 </el-button>
                    <el-button class="font16" type="primary" @click="submitForm('form')" :loading="loading">{{ isEdit ?
                        '确认修改' : '确认发布' }} </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import gameListApi from "@/api/gameConfig/gameList";
import { rentalCreate, rentalDetail, rentalTakeUpdate } from "@/api/rental/account";
import { getToken } from "@/utils/auth";
import draggable from "vuedraggable";
import saomaUpload from "../../../components/upload/saomaUpload.vue";

import makeImgsV3 from "@/utils/makeImgs-v3";

import { uploadFileFn } from "@/api/upload";

import releaseTool from "@/views/tenantPages/goodsList/releaseTool.vue";
export default {
    name: "addDialog",
    components: { draggable, saomaUpload, releaseTool },
    data() {
     
        return {

            isView: false,
            isEdit: false,
            // 表单参数
            form: {
                gameId: "",
                title: "",
                gameName: "",
                gameType: "",
                price: "",
                priceDay: '',
                priceWeek: '',
                priceSub:'',
                account: "",
                password: "",
                costPrice: "",
                otherInfo: "",
                titleImg: "",
                selfNumber: "",
                isSub: 2,
                goodsType: 1,
                isAutoImg: "",
                qufuIds: [],
                yingdi: "",
                urlArr: [],
            },
            title: '发布游戏账号',
            dialogVisible: false,

            qufuTree: [],
            gameList: [],
            loading: false,
            rules: {
                account: [
                    { required: true, message: "请输入账号", trigger: "blur" },
                ],
                gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
                qufuIds: [{ required: true, message: "请选择区服", trigger: "change" }],
                title: [{ required: true, message: "请输入标题", trigger: "blur" }],
                price: [
                    { required: true, message: '时租价格不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const v = parseFloat(value);
                            if (isNaN(v) || v < 0.01) callback(new Error('价格不能小于0.01'));
                            else callback();
                        }, trigger: 'blur'
                    }
                ],
                priceDay: [
                    { required: true, message: '日租价格不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (this.form.isSub !== 1) return callback();
                            const v = parseFloat(value);
                            if (isNaN(v) || v < 0.01) callback(new Error('价格不能小于0.01'));
                            else callback();
                        }, trigger: 'blur'
                    }
                ],
                priceWeek: [
                    { required: true, message: '周租价格不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (this.form.isSub !== 1) return callback();
                            const v = parseFloat(value);
                            if (isNaN(v) || v < 0.01) callback(new Error('价格不能小于0.01'));
                            else callback();
                        }, trigger: 'blur'
                    }
                ],
                priceSub: [
                    { required: () => this.form.isSub === 1, message: '预付款金额不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const v = parseFloat(value);
                            if (isNaN(v) || v < 0.01) callback(new Error('价格不能小于0.01'));
                            else callback();
                        }, trigger: 'blur'
                    }
                ],
            },

            qufuProps: {
                value: "id",
                label: "fieldName",
                children: "childGameAttributes",
                expandTrigger: "hover",
            },

            makeTitleImgBtnLoading: false,
            makeDetailImgBtnLoading: false,
            titleImgList: [],
            uploadImgUrl: "",
            infoInputed: false,
            imgFileList: [],
            newImages: [], //编辑的时候新增加的图片，新增的时候新增加的图片

            infoData: {
                isAutoImg: "",
            },
            attrs: [],
            editId: ''
        }
    },
    computed: {
        userInfo() {
            return this.$store.getters.userInfo;
        },
    },
    created() {
        this.headers = {
            Authorization: "Bearer " + getToken(),
        };
        this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";

    },
    methods: {
        async open(flag, id) {
            await this.getGameList();
            if (this.gameList.length == 0) {
                return;
            }
            if (flag == "add") {
                this.title = '发布游戏账号'
                this.clearDetails()
            } else {
                this.isEdit = true
                this.editId = id
                this.openOld(id);
            }
            this.dialogVisible = true;
        },
        clearDetails() {
            
            const allData = JSON.parse(JSON.stringify(this.form));
              delete allData.title;
            delete allData.price;
            delete allData.priceDay;
            delete allData.priceWeek;
            delete allData.account;
            delete allData.password;
            delete allData.titleImg;
            delete allData.urlArr;
            delete allData.selfNumber;
            delete allData.goodsType;
            delete allData.otherImg;
            this.infoData = { ...allData, reset: true };
        },
        openOld(id) {
            this.title = '编辑游戏账号'
            this.loading = true;
            rentalDetail(id).then(res => {
                this.loading = false;
                let allData = JSON.parse(JSON.stringify(res.data));
                allData.isAutoImg = 1;

                this.form = res.data;

                this.formatFields(allData);
                this.getQufuTree(this.form.gameId);
            })
        },
        // 扫码上传结束
        saomaEnd(e, key) {
            if (key == "titleImg" && e.length) {
                this.form.titleImg = e[0].url;
                this.titleImgList = [
                    {
                        ...e[0],
                    },
                ];
            }

            if (key == "otherImg" && e.length) {
                e.forEach((r) => {
                    this.otherImgList.push(r);
                });
            }
        },
        // 游戏列表
        async getGameList() {
            let res = await gameListApi.getCustomGamelist();
            this.gameList = res.data;
        },
        // 游戏选择改变
        async gameChange(e) {
            if (this.form.qufu) {
                this.form.qufu = "";
            }

            this.form.gameName = "";
            this.form.gameType = "";
            this.form.qufuIds = [];
            if (e) {
                for (let i = 0; i < this.gameList.length; i++) {
                    if (this.gameList[i].id == e) {
                        this.form.gameName = this.gameList[i].name;
                        this.form.gameType = this.gameList[i].type;
                    }
                }
                this.infoData = {
                    gameId: this.form.gameId,
                    gameType: this.form.gameType,
                    gameName: this.form.gameName,
                    reset: true
                };
                await this.getQufuTree();
            }
        },
        // 整理左侧字段和右侧字段
        formatFields(allData, flag) {
            let title = allData.title
                ? allData.title
                : allData.des
                    ? allData.des.slice(0, 50)
                    : "";
            title = title.replace(/\n/g, "");
            let obj = {
                title: title,
                price: allData.price,
                priceDay: allData.priceDay,
                priceWeek: allData.priceWeek,
                account: allData.account,
                password: allData.password,
                titleImg: allData.titleImg,
                urlArr: allData.urlArr,
                selfNumber: allData.selfNumber,
                goodsType: allData.goodsType,
                isSub: allData.isSub,
                priceSub: allData.priceSub,
                otherImg: allData.otherImg,
            };

            obj.gameId = allData.gameId;
            obj.gameType = allData.gameType;
            obj.gameName = allData.gameName;
            obj.systemId = allData.systemId || "";
            obj.systemName = allData.systemName || "";
            obj.carrierId = allData.carrierId || "";
            obj.carrierName = allData.carrierName || "";
            obj.groupId = allData.groupId || "";
            obj.groupName = allData.groupName || "";
            obj.serverId = allData.serverId || "";
            obj.serverName = allData.serverName || "";


            delete allData.title;
            delete allData.price;
            delete allData.priceDay;
            delete allData.priceWeek;
            delete allData.account;
            delete allData.password;
            delete allData.titleImg;
            delete allData.urlArr;
            delete allData.selfNumber;
            delete allData.priceSub;
             delete allData.isSub;
            delete allData.goodsType;
            delete allData.otherImg;


            obj.qufuIds = allData.gameType == 1 ? [allData.groupId, allData.serverId] : [
                allData.systemId,
                allData.carrierId,
                allData.groupId,
                allData.serverId,
            ];

            this.form = obj;
            console.log("%c Line:202 🍒 obj", "color:#33a5ff", obj,);
            this.allData = allData;
            if (obj.urlArr) {
                this.imgFileList = obj.urlArr;
            }
            if (obj.otherImg) {
                this.otherImgList = JSON.parse(obj.otherImg);
            }
            if (obj.titleImg) {
                this.titleImgList = [{ url: obj.titleImg, name: "" }];
            }

            this.infoData = { ...this.allData, reset: true };
        },
        async getQufuTree(gameId) {
            this.qufuTree = [];
            let obj = {};
            obj.gameId = gameId || this.form.gameId;
            try {
                const res = await gameListApi.qufuTreeGetByGameId(obj)
                this.qufuTree = [...res.data];
            } catch (error) {

            }
        },
        // 区服改变
        qufuChange(e) {
            // console.log("%c Line:220 🍐 e", "color:#33a5ff", e);
            this.form.systemName = "";
            this.form.systemId = ''
            this.form.carrierName = "";
            this.form.groupName = "";
            this.form.serverName = "";


            this.form.carrierId = "";
            this.form.groupId = "";
            this.form.serverId = "";
            if (!e || e.length == 0) {
            } else {
                this.getQufuForQufuIds();
            }
        },
        // 处理区服
        getQufuForQufuIds() {
            // 处理区服
            let qufu = "";
            if (this.form.gameType == 1) {
                // 端游
                this.qufuTree.forEach((daqu) => {
                    if (daqu.id == this.form.qufuIds[0]) {
                        qufu += daqu.fieldName;
                        this.form.groupId = daqu.id;
                        this.form.groupName = daqu.fieldName;
                        if (daqu.childGameAttributes && daqu.childGameAttributes.length) {
                            daqu.childGameAttributes.forEach((fu) => {
                                if (fu.id == this.form.qufuIds[1]) {
                                    qufu += fu.fieldName;
                                    this.form.serverId = fu.id;
                                    this.form.serverName = fu.fieldName;
                                }
                            });
                        }
                    }
                });
            } else {
                // 手游
                this.qufuTree.forEach((sys) => {
                    if (sys.id == this.form.qufuIds[0]) {
                        qufu += sys.fieldName;
                        this.form.systemId = sys.id;
                        this.form.systemName = sys.fieldName;
                        if (sys.childGameAttributes && sys.childGameAttributes.length) {
                            sys.childGameAttributes.forEach((carr) => {
                                if (carr.id == this.form.qufuIds[1]) {
                                    qufu += carr.fieldName;
                                    this.form.carrierId = carr.id;
                                    this.form.carrierName = carr.fieldName;
                                    if (
                                        carr.childGameAttributes &&
                                        carr.childGameAttributes.length
                                    ) {
                                        carr.childGameAttributes.forEach((daqu) => {
                                            if (daqu.id == this.form.qufuIds[2]) {
                                                qufu += daqu.fieldName;
                                                this.form.groupId = daqu.id;
                                                this.form.groupName = daqu.fieldName;
                                                if (
                                                    daqu.childGameAttributes &&
                                                    daqu.childGameAttributes.length
                                                ) {
                                                    daqu.childGameAttributes.forEach((fu) => {
                                                        if (fu.id == this.form.qufuIds[3]) {
                                                            qufu += fu.fieldName;
                                                            this.form.serverId = fu.id;
                                                            this.form.serverName = fu.fieldName;
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                });
            }
            this.form.qufu = qufu;
            // 通知右侧组件  区服更新
            this.$refs.releaseTool.updateQufu({
                systemId: this.form.systemId,
                systemName: this.form.systemName,
                carrierId: this.form.carrierId,
                carrierName: this.form.carrierName,
                groupId: this.form.groupId,
                groupName: this.form.groupName,
                serverId: this.form.serverId,
                serverName: this.form.serverName,
            });
            // this.GetIsKuaiSu(this.form.gameId)
        },



        handlePictureCardPreview(file) {
            this.$viewerApi({
                images: [file.url],
            });
        },
        // 处理图片预览效果
        handlePreviewNew(index) {
            let arr = [];
            this.imgFileList.map((item) => {
                arr.push(item.url);
            });
            this.$viewerApi({
                images: arr,
                options: {
                    initialViewIndex: index,
                },
            });
        },
        imgPreview(url) {
            this.$viewerApi({
                images: [url],
            });
        },
        // 通知详情组件保存
        postInfoSave() {
            this.infoInputed = false;
            this.$refs.releaseTool.submitForm();
        },

        uploadNumber(file, fileList) {
            //限制图片数量
            this.$modal.msgError("最多只能上传100张图片");
        },
        // 详情图片上传成功
        handleUploadSuccess(res, file, fileList) {
            if (fileList.every((item) => item.status == "success")) {
                let tempArr = this.imgFileList.map((m) => {
                    return m.url;
                });
                fileList.forEach((t) => {
                    if (
                        t.url.indexOf("blob:") > -1 &&
                        t.response &&
                        t.response.data &&
                        t.response.data.filePath
                    ) {
                        if (!tempArr.includes(t.response.data.filePath)) {
                            this.imgFileList.push({
                                url: t.response.data.filePath,
                                name: "",
                            });
                        }
                        return true;
                    }
                });
            }

        },
        /** 一键生成主图 */
        async makeTitleImg() {
            // 处理所有的填写项
            let allForm = {};
            let form1 = JSON.parse(JSON.stringify(this.form));
            let form2 = JSON.parse(JSON.stringify(this.allData));
            allForm = {
                ...form1,
                ...form2,
            };
            // 处理多选项，拼接duoxuan详情的LIST

            let img = "";
            let str = "";
            this.attrs.forEach((t) => {
                if (t.fieldType == "checkbox" || t.fieldType == "boxradio") {
                    if (allForm[t.aavName]) {
                        str = str + allForm[t.aavName] + ",";
                    }
                }
            });

            // 生成
            let obj = JSON.parse(JSON.stringify(allForm));
            let list2 = JSON.parse(JSON.stringify(this.attrs));
            obj.shopName = this.$store.state.user.shopInfo.tenantName;
            img = await makeImgsV3.makeTitleImgStart(obj, str, list2, this.huoquData);
            return img;
        },
        // 一键获取首图
        async openGetInfoDialog() {
            // 判断有没有填写详情
            await this.postInfoSave();
            if (!this.infoInputed) {
                return this.$message.error("请将右侧商品详情信息填写完整！");
            }
            this.makeTitleImgBtnLoading = true;
            let img = "";
            try {
                img = await this.makeTitleImg();
                this.makeTitleImgBtnLoading = false;
            } catch {
                this.makeTitleImgBtnLoading = false;
            }
            // 上传生成的base64图片
            if (img) {
                let titImg = this.base64ToBlob(img);
                // console.log("%c Line:1300 🍐 titImg", "color:#33a5ff", titImg);
                const resFile = await uploadFileFn(titImg, this.userInfo.tenantId);
                const imgUrl = qiniu.imageMogr2(
                    {
                        strip: true, // 布尔值，是否去除图片中的元信息
                        quality: 90, // 图片质量，取值范围1-100
                        format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
                    },
                    resFile.key,
                    resFile.domain
                );
                this.form.titleImg = decodeURIComponent(imgUrl);
                this.titleImgList = [{ url: imgUrl, name: "" }];
            }
        },

        // 限制图片大小
        beforeUploadImg(file) {
            if (file.size / 1024 / 1024 > 20) {
                this.$message.error("上传的图片不能超过20MB！请压缩后再传！");
                return false;
            } else {
                return true;
            }
        },

        // 上传图片
        async uploadImgs(file) {
            // 获取压缩后的文件流
            let compreeBolb = await this.compressImage(file);
            // console.log(
            //   "%c Line:468 🎂 压缩后compreeBolb",
            //   "color:#33a5ff",
            //   compreeBolb
            // );
            // const formData = new FormData();
            // formData.append("file", compreeBolb); //压缩后的文件会自动转换成二进制文件流类型
            //上传图片到后台
            try {
                // let uploadImg = await postUpload(formData);
                const resFile = await uploadFileFn(compreeBolb, this.userInfo.tenantId);
                const imgUrl = qiniu.imageMogr2(
                    {
                        strip: true, // 布尔值，是否去除图片中的元信息
                        quality: 90, // 图片质量，取值范围1-100
                        format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
                    },
                    resFile.key,
                    resFile.domain
                );
                file.data = {
                    filePath: decodeURIComponent(imgUrl),
                };
                file.code = 200;
                return file;
            } catch {
                file.code = 500;
                return file;
            }
        },

        // 详情图片删除
        handleRemove(url) {
            // console.log("%c Line:495 🍎 url", "color:#4fff4B", url);
            const that = this;
            // 1.获取将要删除图片的临时路径
            // const filePath = response.url;
            // 2.找到图片对应的索引值
            this.imgFileList.forEach(function (element, key) {
                if (element.url === url) {
                    that.imgFileList.splice(key, 1); //回显的图片
                }
            });
            // this.imgShowList.forEach(function (element, key) {
            //   if (element.url === filePath) {
            //     that.imgShowList.splice(key, 1); //回显的图片
            //   }
            // });
            this.newImages.forEach(function (element, key) {
                if (element.url === url) {
                    that.newImages.splice(key, 1); //新上传的图片
                }
            });
        },    // 标题图片移除
        handleAvatarRemove(response, file) {
            this.form.titleImg = "";
            this.titleImgList = [];
        },
        // 标题图片上传成功
        handleAvatarSuccess(res, file) {
            if (res.code == 200) {
                let url = res.data.filePath;
                let name = res.data.fileName;
                let param = {};
                param.url = url;
                param.name = name;
                this.titleImgList.push(param);
                this.form.titleImg = res.data.filePath;
            }
        },

        // 图片转换
        base64ToBlob(code) {
            let parts = code.split(";base64,");
            let contentType = parts[0].split(":")[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], { type: contentType });
        },

        // 点击生成详情图
        async getDetailImgs() {
            // 判断有没有填写详情
            await this.postInfoSave();
            if (!this.infoInputed) {
                return this.$message.error("请将右侧商品详情信息填写完整！");
            }
            // 和平精英 英雄联盟 英雄联盟手游 无畏契约 王者荣耀
            if (
                this.form.gameId == 5 ||
                this.form.gameId == 29 ||
                this.form.gameId == 3 ||
                this.form.gameId == 6 ||
                this.form.gameId == 2 ||
                this.form.gameId == 25 ||
                this.form.gameId == 10 ||
                this.form.gameId == 12 ||
                this.form.gameId == 67 ||
                this.form.gameId == 8 ||
                this.form.gameId == 7
            ) {
                this.getDetailImgsNew();
            } else {
                this.makeDetailImgBtnLoading = true;
                let img = "";
                try {
                    img = await this.makeDetailImgs();
                    this.makeDetailImgBtnLoading = false;
                } catch {
                    this.makeDetailImgBtnLoading = false;
                }
                // 上传生成的base64图片
                let detailImg = this.base64ToBlob(img);

                const resFile = await uploadFileFn(detailImg, this.userInfo.tenantId);
                const imgUrl = qiniu.imageMogr2(
                    {
                        strip: true, // 布尔值，是否去除图片中的元信息
                        quality: 90, // 图片质量，取值范围1-100
                        format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
                    },
                    resFile.key,
                    resFile.domain
                );
                this.imgFileList.push({ url: decodeURIComponent(imgUrl), name: "" });
                // this.imgShowList.push({ url: res.msg, name: "" });
            }
        },
        // 点击生成多张详情图 新版
        async getDetailImgsNew() {
            // 判断有没有填写详情
            await this.postInfoSave();
            if (!this.infoInputed) {
                return this.$message.error("请将右侧商品详情信息填写完整！");
            }
            // 处理多选项，拼接duoxuan详情的LIST
            // 处理所有的填写项
            let allForm = {};
            let form1 = JSON.parse(JSON.stringify(this.form));
            let form2 = JSON.parse(JSON.stringify(this.allData));
            allForm = {
                ...form1,
                ...form2,
            };
            let list = [{}];
            let arrInd = 0;
            this.attrs.forEach((t) => {
                if (t.fieldType == "checkbox" && t.isEnable === "0") {
                    if (
                        allForm[t.aavName] &&
                        t.childAttributes &&
                        (this.form.gameId != 29 ||
                            (this.form.gameId == 29 && t.aavName != "f2"))
                    ) {
                        list[arrInd] = {
                            list: [],
                            name: t.fieldName,
                        };
                        for (let j = 0; j < t.childAttributes.length; j++) {
                            const k = t.childAttributes[j];
                            if (allForm[t.aavName].includes(k.id) && k.imgUrl) {
                                list[arrInd].list.push(k);
                            }
                        }
                        arrInd++;
                    }
                } else if (t.fieldType == "boxradio" && t.isEnable === "0") {
                    if (allForm[t.aavName] && t.childAttributes) {
                        list[arrInd] = {
                            list: [],
                            name: t.fieldName,
                        };
                        for (let j = 0; j < t.childAttributes.length; j++) {
                            let k = t.childAttributes[j];
                            if (k.childGameAttributes) {
                                for (let l = 0; l < t.childGameAttributes.length; l++) {
                                    let c = t.childGameAttributes[l];
                                    if (allForm[t.aavName].includes(c.id)) {
                                        list[arrInd].list.push(c);
                                    }
                                }
                            }
                        }
                        arrInd++;
                    }
                }
            });
            this.makeDetailImgBtnLoading = true;
            allForm.shopName = this.$store.state.user.shopInfo.tenantName;
            let imgs = await makeImgsV3.makeDetailImgMultiple(
                allForm,
                list,
                this.attrs
            );
            for (let i = 0; i < imgs.length; i++) {
                // 上传生成的base64图片
                let detailImg = this.base64ToBlob(JSON.parse(imgs[i]));
                // let formData = new FormData();
                // formData.append("file", detailImg);
                const resFile = await uploadFileFn(detailImg, this.userInfo.tenantId);
                const imgUrl = qiniu.imageMogr2(
                    {
                        strip: true, // 布尔值，是否去除图片中的元信息
                        quality: 90, // 图片质量，取值范围1-100
                        format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
                    },
                    resFile.key,
                    resFile.domain
                );
                this.imgFileList.push({ url: decodeURIComponent(imgUrl), name: "" });
            }
            this.makeDetailImgBtnLoading = false;
        },

        // 一键获取信息后  自动设置标题
        setTitle(e) {
            if (e && e.length) {
                const title = e.replace(/[\r\n]+/g, "").substr(0, 200);
                this.$set(this.form, "title", title)
            }
        },

        getInfoData(e) {
            this.allData = JSON.parse(JSON.stringify(e));
            if(this.allData&&!this.allData.des) {
                this.infoInputed = false;
            }else {
                this.infoInputed = true;
            }
            
        },

        // attr改变
        attrChange(e) {
            this.attrs = e;
        },
        reset() {
            this.qufuTree = [];
            this.selectedPhone = "";
            this.$refs["form"].resetFields();
            this.form.titleImg = "";
            this.form.urlArr = null;
            this.form.title = null;
            this.form.otherImg = null;
            this.imgFileList = [];
            this.titleImgList = [];
            this.newImages = [];
            this.otherImgList = [];
            this.attrs = [];
            this.allData = {};

        },
        close() {
           
            // 关闭了弹窗
            this.reset();
            this.dialogVisible = false;
            this.btnLoading = false;
            this.makeTitleImgBtnLoading = false;
            this.makeDetailImgBtnLoading = false;
            this.$emit("close");
          
        },
        closeFn() {
            this.dialogVisible = false;
        },
        submitForm() {
            console.log("submit!", this.form);
            this.$refs["form"].validate(async (valid) => {
                if (valid) {
                    await this.postInfoSave();
                     if (!this.infoInputed) {
                     this.$alert("请将右侧商品详情信息填写完整！");
                     return;
                     }
                    let tip = '确定发布该游戏账号吗？'
                    this.$confirm(
                        tip,
                        "提示",
                        {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning",
                        }
                    )
                        .then(async () => {
                            this.submitFormSure();
                        })
                        .catch(() => { });
                } else {
                    this.$alert("请填写完整！");
                }

            });
        },

        submitFormSure() {
            let imgFileList = []
            if (this.imgFileList && this.imgFileList.length) {
                this.imgFileList.forEach(img => {
                    imgFileList.push({
                        name: '',
                        url: img.url
                    })
                })
            }
            if (this.newImages && this.newImages.length) {
                let newArr = [];
                this.newImages.forEach((img) => {
                    newArr.push({
                        name: img.name,
                        url: img.response.data.filePath,
                    });
                });
                this.form.urlArr = imgFileList.concat(newArr);
            } else {
                this.form.urlArr = imgFileList;
            }

            let obj = {
                ...this.form,
                ...this.allData,
            };
            let that = this
            // 去除账号两端空格
            if (obj.account) obj.account = obj.account.trim()
            if (obj.password) obj.password = obj.password.trim()
            if (this.isEdit) {
                obj.id = this.editId;
                rentalTakeUpdate(obj).then((response) => {
                    // this.$modal.msgSuccess("编辑成功");
                    this.attrs = [];
                    // 成功后提示
                    this.closeFn();
                    this.dialogVisible = false
                    this.$alert("修改商品成功！", "提示", {
                        confirmButtonText: "确定",
                        callback: (action) => {
                            console.log("action", '审核通过');
                            that.$parent.getList();
                            
                        },
                    });
                });

            } else {
                console.log("新增", obj);
                rentalCreate(obj).then((response) => {
                    this.$modal.msgSuccess("新增成功");
                    this.attrs = [];
                    this.$emit("success");
                    this.close();
                });

            }
        },
    }
};


</script>
<style scoped lang="scss">
.ceshifont {
    font-family: myFontruihei5;
}

.add-edit-box {
    position: relative;
    height: calc(100% - 30px);

    >.flex {
        height: 100%;
    }

    .game-box {
        flex-wrap: wrap;

        .select-game-item {
            width: 60px;
            text-align: center;
            color: #666;
            font-size: 12px;
            margin-right: 5px;
            margin-bottom: 8px;
            cursor: pointer;

            overflow: hidden;

            .img {
                width: 50px;
                height: 50px;
                border-radius: 8px;
                overflow: hidden;
                position: relative;
                margin: 0 auto;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            &.active {
                color: #6c5dd3;
                font-weight: bold;
            }

            .sign {
                width: 50px;
                height: 20px;
                line-height: 22px;
                text-align: center;
                font-size: 11px;
                background-color: #6c5dd3;
                color: #fff;
                position: absolute;
                top: -2px;
                left: -16px;
                transform: rotate(-45deg);
            }
        }
    }
}

.center {
    padding-top: 10px;
    border-top: 1px solid #f3f3f3;

    .el-button {
        width: 200px;
        height: 36px;
    }
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.boxradioitem {
    padding: 15px;
    border: 1px dashed #999;
    border-radius: 10px;
}

.step-box {
    width: 100%;
    // padding: 10px;
    background-color: $fff;
    // margin-bottom: 16px;
}

.sub-tit {
    margin-bottom: 15px;
}

.yitian {
    color: $green;
    margin-left: 10px;
    cursor: pointer;
}

.weitian {
    color: $yellow;
    margin: 0 10px;
    cursor: pointer;
}

.video-view {
    width: 280px;
    height: 150px;
    align-items: flex-start;

    .el-icon-delete {
        width: 20px;
        height: 20px;
        flex-shrink: 0;
        font-size: 20px;
        margin-left: 10px;
        color: #666;
        cursor: pointer;
    }

    video {
        width: 280px;
        height: 150px;
        border-radius: 10px;
    }
}

.phone-box {
    margin-left: 15px;
    align-items: center;

    .name {
        white-space: nowrap;
        width: 90px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.add_dialog ::v-deep .el-dialog__body {
    height: calc(100vh - 60px) !important;
    max-height: calc(100vh - 50px) !important;
}

.form-box {
    width: 40%;
    min-width: 650px;
    flex-shrink: 0;
    height: 100%;
    overflow-y: auto;
    padding-right: 15px;
    box-sizing: border-box;
    border-right: 1px solid #f3f3f3;
}

.release-page {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
}

.uploader {
    display: flex;
    // align-items: center;
    flex-wrap: wrap;

    .upload-list {
        margin-right: 10px;
        margin-bottom: 10px;
        width: 100px;
        height: 100px;
        border-radius: 6px;
        overflow: hidden;
        border: 1px solid #eee;
        position: relative;

        &:hover {
            .icon-container {
                display: block;
                transition: all 0.5s;
            }
        }

        .icon-container {
            position: absolute;
            display: none;
            transition: all 0.5s;
            width: 100%;
            height: 100%;
            line-height: 100px;
            color: #fff;
            font-size: 20px;
            text-align: center;
            border-radius: 8px;
            top: 0;
            left: 0;
            background-color: rgba(0, 0, 0, 0.5);
            cursor: pointer;

            span {
                margin: 0 10px;
                cursor: pointer;
            }
        }
    }

    .imgs {
        position: absolute;
        top: 0;
        right: 0;
    }
}

::v-deep .el-dialog__body {
    padding-top: 10px !important;
}

::v-deep .upload_img_box .el-form-item {
    width: 200px !important;
}

.price-label {
    margin-right: 5px;
}
</style>